package com.aispeech.imgany.ui;


import static com.aispeech.imgany.MyApplication.getContext;
import static com.aispeech.imgany.MyApplication.width;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aispeech.imgany.ControlService;
import com.aispeech.imgany.MyApplication;
import com.aispeech.imgany.R;
import com.aispeech.imgany.data.TaobaoItem;
import com.aispeech.imgany.engineSdk.VoiceEngineManage;
import com.aispeech.imgany.net.IPostImgListener;
import com.aispeech.imgany.net.PostImg;
import com.aispeech.imgany.utils.DipPixelUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONObject;

public class ScreenShotUtil {

    private final static String TAG = "ScreenShotUtil";
//    private final String postUrl = "http://192.168.3.100:8000/upload";

    private static ScreenShotUtil mInstance;
    public WindowManager mWindowManager;
    private LayoutInflater mLayoutInflater;
    ImageView iv_screen;
    private View view_left;
    private View view_right;
    private View content_animator;

    private View view_content;
    private TextView part_one;
    private TextView part_two;
    private ListView mLvTbItems;
    private ImageView mImgTbItemQrcode;
    private ItemAdapter itemAdapter;

    private View view;
    private View dataContent;
    private WindowManager.LayoutParams mParams;// 窗口的属性
    private WindowManager.LayoutParams mShowParams;
    private static String recognize_text;
    private static String recognize_title;
    private static String recognize_from;

    private List<TaobaoItem> taobaoList = new ArrayList<>();

    public List<TaobaoItem> getTaobaoList() {
        return taobaoList;
    }

    public static boolean isShowDataContent = false;

    public static ScreenShotUtil getInstance() {
        if (null == mInstance) {
            mInstance = new ScreenShotUtil();
        }
        return mInstance;
    }

    public ScreenShotUtil() {

    }

    private final static int SHOWTOAST = 1;
    private final static int LOADDONE = 2;
    private final static int OVERTIME = 3;
    private final static int EMPTY = 4;
    private static Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Log.d(TAG, "handleMessage: msg what =" + msg.what);
            switch (msg.what) {
                case SHOWTOAST:
                    SelfDurationToast.makeText(MyApplication.getContext(), "", 9000, 2).show();
                    break;
                case LOADDONE:
//                    String text = (String) msg.obj;
                    SelfDurationToast.loadDoneAndShow();
                    break;
                case OVERTIME:
                    SelfDurationToast.handlerOver();
                    break;
                case EMPTY:
                    SelfDurationToast.handlerEmpty();
                    break;
            }
        }
    };

    public void init(Context mContext) {
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

        mParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSPARENT);
        mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;// 系统提示window
        mParams.format = PixelFormat.TRANSLUCENT;// 支持透明
        mParams.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;// 窗口的宽和高
        mParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.gravity = Gravity.LEFT | Gravity.TOP;
        mParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        mParams.y = 0;
        mParams.x = 0;
        mParams.windowAnimations = android.R.style.Animation_Toast;
        view = mLayoutInflater.inflate(R.layout.service_animator, null);

        iv_screen = (ImageView) view.findViewById(R.id.iv_screenshot);
        content_animator = view.findViewById(R.id.animator_content);
        view_left = view.findViewById(R.id.left_view);
        view_right = view.findViewById(R.id.right_view);
    }


    public void initDataContent(Context mContext) {
        mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

        mShowParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSPARENT);
        mShowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;// 系统提示window
        mShowParams.format = PixelFormat.TRANSLUCENT;// 支持透明
        mShowParams.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;// 焦点
        mShowParams.width = DipPixelUtil.dip2px(mContext, 220);// 窗口的宽和高
        mShowParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        mShowParams.gravity = Gravity.RIGHT | Gravity.TOP;
        mShowParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        mShowParams.y = 0;
        mShowParams.x = 0;
        mShowParams.windowAnimations = android.R.style.Animation_Toast;
        dataContent = mLayoutInflater.inflate(R.layout.service_data_show, null);

        view_content = dataContent.findViewById(R.id.view_datacontent);
        part_one = (TextView) dataContent.findViewById(R.id.key_word);
        part_two = (TextView) dataContent.findViewById(R.id.key_desc);
        mLvTbItems = (ListView) dataContent.findViewById(R.id.lv_tb_items);
        itemAdapter = new ItemAdapter(mContext, R.layout.lv_taobao_item, taobaoList);
        mLvTbItems.setAdapter(itemAdapter);

        mImgTbItemQrcode = (ImageView) dataContent.findViewById(R.id.img_tbitem_qrcode);
        mImgTbItemQrcode.setVisibility(View.GONE);
    }

    public boolean isContentAlive() {
        return dataContent.getParent() != null && isDataContentAlive;
    }

    private boolean isDataContentAlive = false;

    public void showDataContent() {
        isDataContentAlive = true;
        mWindowManager.addView(dataContent, mShowParams);// 添加窗口
        if (recognize_from.equals("baidu") || recognize_from.equals("sogou")) {
            part_one.setText(recognize_title);
            part_two.setText(recognize_text);
            part_two.setVisibility(View.VISIBLE);
            mLvTbItems.setVisibility(View.GONE);
            mImgTbItemQrcode.setVisibility(View.GONE);
        } else if ("taobao".equals(recognize_from)) {
            part_one.setText(recognize_title);
            part_two.setVisibility(View.GONE);
            mLvTbItems.setVisibility(View.VISIBLE);
            itemAdapter.notifyDataSetChanged();
        }
    }

    private void requestPic(String imagePath) {
//        VoiceEngineManage.getInstance().playTTS("开始图像检索");
        PostImg postImg = new PostImg(new IPostImgListener() {

            @Override
            public void onResult(String searchResult) {
                Log.d(TAG, "onResult with: searchResult = " + searchResult + "");
            }

            @Override
            public void onError(String einfo) {
//                VoiceEngineManage.getInstance().startWakeup();
                Log.d(TAG, "onError with: einfo = " + einfo + "");
            }


            @Override
            public void onDetailsResult(String details) {
                Log.d(TAG, "onDetailsResult with: baike = " + details + "");
                recognize_text = "";
                recognize_title = "";
                recognize_from = "";
                taobaoList.clear();

                String entity = null;
                String content = null;
                try {
                    JsonElement element = new JsonParser().parse(details);
                    JsonObject obj = element.getAsJsonObject();
                    if (obj.has("from") && !TextUtils.isEmpty(obj.get("from").getAsString())) {
                        String from = obj.get("from").getAsString();
                        recognize_from = from;
                        entity = obj.get("guessWord").getAsString();

                        if ("baidu".equals(from)) {
                            JsonObject joDet = obj.getAsJsonObject("details");
                            content = joDet.get("synop").getAsString();
                        } else if ("sogou".equals(from)) {
                            JsonElement jeDetails = new JsonParser().parse(obj.get("details").getAsString());
                            if (!jeDetails.isJsonNull()) {
                                JsonObject obj2 = jeDetails.getAsJsonObject();
                                if (obj2.has("content")) {
                                    content = obj2.get("content").getAsString();
                                }
                            }
                        } else if ("taobao".equals(from)) {
                            JsonElement jeDetails = new JsonParser().parse(obj.get("details").getAsString());
                            JsonObject joDetails = jeDetails.getAsJsonObject();
//                            JsonObject joDetails = obj.get("details").getAsJsonObject();
                            JsonObject joData = joDetails.getAsJsonObject("data");
                            JsonArray jaCollections = joData.getAsJsonArray("collections");
                            JsonObject joSimilar = jaCollections.get(0).getAsJsonObject();
                            JsonArray jaItems = joSimilar.getAsJsonArray("auctions");
                            for (JsonElement je : jaItems) {
                                if (!je.isJsonNull()) {
                                    JsonObject jeo = je.getAsJsonObject();
                                    String title = jeo.get("title").getAsString();
                                    String picUrl = "https:" + jeo.get("pic_url").getAsString();
                                    String dtlUrl = "https:" + jeo.get("detail_url").getAsString();

                                    String itemLoc = jeo.get("item_loc").getAsString();
                                    String viewSales = jeo.get("view_sales").getAsString();
                                    String commentCount = jeo.get("comment_count").getAsString();

                                    Log.d(TAG, "onDetailsResult: title = " + title + "\n pic_url = " + picUrl + "\n detail_url = " + dtlUrl);
                                    Log.d(TAG, "onDetailsResult: itemLoc = " + itemLoc + "\n viewSales = " + viewSales + "\n commentCount = " + commentCount);

                                    taobaoList.add(new TaobaoItem(picUrl, title, dtlUrl, itemLoc, viewSales, commentCount));
                                }
                            }
                        }
                        Log.d(TAG, "onDetailsResult: from = " + from + " \n entity = " + entity + " \n content = " + content);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (!TextUtils.isEmpty(entity)) {
                    recognize_text = content;
                    if ("taobao".equals(recognize_from)){
                        VoiceEngineManage.getInstance().playTTS("找到一大波、" + entity);
                    }else {
                        VoiceEngineManage.getInstance().playTTS("有可能是、" + entity);
                    }
                    if (!TextUtils.isEmpty(content)) {
                        recognize_title = entity;
                    }
                    handler.sendEmptyMessage(LOADDONE);
                }

                else {
                    handler.sendEmptyMessage(EMPTY);
                }

            }
        });

        HashMap margs = new HashMap();
        margs.put("want", ControlService.currentWakeupWord);
        File fimg = new File(imagePath);
        margs.put("img", fimg);
        postImg.uploadFile(margs);
    }

    public void ShotDone(String imagePath) {
        mWindowManager.addView(view, mParams);// 添加窗口
        startAnimator(imagePath);
    }

    /**
     * 通过传入的content来生成二维码显示
     *
     * @param content 生成二维码的文本
     */
    public void showQRCodeWithUrl(String content) {
        int width = DipPixelUtil.dip2px(getContext(), 160);// 窗口的宽和高
        int height = width;
        Log.d(TAG, "showQRCodeWithUrl with: content = " + content + "");
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x00000000;
                    } else {
                        pixels[i * width + j] = 0xffffffff;
                    }
                }
            }
            mImgTbItemQrcode.setImageBitmap(Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565));
            mImgTbItemQrcode.setVisibility(View.VISIBLE);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    private void startAnimator(final String imagePath) {
        AnimatorSet set = new AnimatorSet();

        view_left.setTranslationX(-MyApplication.height / 2);
        view_right.setTranslationX(MyApplication.height / 2);
        ObjectAnimator animator_left = ObjectAnimator.ofFloat(view_left, "translationX", -MyApplication.height / 2, 0, -MyApplication.height / 2);
        ObjectAnimator animator_right = ObjectAnimator.ofFloat(view_right, "translationX", MyApplication.height / 2, 0, MyApplication.height / 2);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                content_animator.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                content_animator.setVisibility(View.GONE);
//                requestCapturePermission();
                Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                iv_screen.setImageBitmap(bitmap);
                sendToRequestAnimator(imagePath);
            }
        });
        set.play(animator_left).with(animator_right);
        set.setDuration(200);
        set.setStartDelay(300);
        set.start();
    }

    private void sendToRequestAnimator(final String imagePath) {
        float locateX = (float) (width * 2.5 / 4);
        float locateY = MyApplication.height * 3 / 4;

        AnimatorSet set = new AnimatorSet();
        ObjectAnimator animator_TRX = ObjectAnimator.ofFloat(iv_screen, "translationX", 0f, locateY);
        ObjectAnimator animator_TRY = ObjectAnimator.ofFloat(iv_screen, "translationY", 0f, locateX);
        ObjectAnimator animator_SX = ObjectAnimator.ofFloat(iv_screen, "scaleX", 1f, 1 / 4f);
        ObjectAnimator animator_SY = ObjectAnimator.ofFloat(iv_screen, "scaleY", 1f, 1 / 4f);
        iv_screen.setPivotX(0);
        iv_screen.setPivotY(0);
        set.playTogether(animator_TRX, animator_TRY, animator_SX, animator_SY);
        set.setStartDelay(200);
        set.setDuration(200);

//        ObjectAnimator anmator_TRX_repect = ObjectAnimator.ofFloat(iv_screen, "translationX", locateY, locateY + 20, locateY, locateY + 20, locateY);
//        anmator_TRX_repect.setDuration(800);
//        anmator_TRX_repect.setStartDelay(200);

        ObjectAnimator anmator_TRX_dismiss = ObjectAnimator.ofFloat(iv_screen, "translationX", locateY, MyApplication.height);
        anmator_TRX_dismiss.setInterpolator(new AccelerateInterpolator());
        anmator_TRX_dismiss.setDuration(500);
        anmator_TRX_dismiss.setStartDelay(500);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mWindowManager.removeView(view);
                handler.sendEmptyMessage(SHOWTOAST);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                requestPic(imagePath);
            }
        });
        animatorSet.playSequentially(set, anmator_TRX_dismiss);
        animatorSet.start();

    }

    public void dismissDataContent() {
        if (dataContent != null && dataContent.getParent() != null) {
            isDataContentAlive = false;
            mWindowManager.removeView(dataContent);
        }
    }

    private int getStatusBarHeight(Context mContext) {
        int statusBarHeight = 0;
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = mContext.getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }

    class ItemAdapter extends ArrayAdapter {

        private final int resourceId;

        public ItemAdapter(@NonNull Context context, int textViewResourceId, List<TaobaoItem> objects) {
            super(context, textViewResourceId, objects);
            resourceId = textViewResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TaobaoItem tbi = (TaobaoItem) getItem(position);
            View view = LayoutInflater.from(getContext()).inflate(resourceId, null);
            ImageView tbiImg = (ImageView) view.findViewById(R.id.iv_tbi_pic);
            TextView tbiName = (TextView) view.findViewById(R.id.tv_tbi_shopname);
//            tbiImg.setImageResource(tbi.getImgPath());
            Picasso.with(getContext()).load(tbi.getImgPath()).
                resize(300, 300).centerCrop().into(tbiImg);
            tbiName.setText(tbi.getShopName());
            return view;
        }
    }
}
